package top.lyjwn.todo.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.digest.DigestUtils;
import java.util.Base64;

public class AESUtil {

	/**
	 * 密钥算法
	 */
	private static final String ALGORITHM = "AES";
	/**
	 * 加解密算法/工作模式/填充方式
	 */
	private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";

	/**
	 * 生成key
	 */
	//private static SecretKeySpec key = new SecretKeySpec(DigestUtils.md5Hex("").getBytes(), ALGORITHM);

	/**
	 * AES加密
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String encryptData(String data,String key) throws Exception {
		// 创建密码器
		Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
		// 初始化
		SecretKeySpec keySpec = new SecretKeySpec(DigestUtils.md5Hex(key).getBytes(), ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		byte[] encode = Base64.getEncoder().encode(cipher.doFinal(data.getBytes()));
		String encodeStr = new String(encode);
		return encodeStr;
	}

	/**
	 * AES解密
	 * 
	 * @param base64Data
	 * @return
	 * @throws Exception
	 */
	public static String decryptData(String base64Data,String key) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
		SecretKeySpec keySpec = new SecretKeySpec(DigestUtils.md5Hex(key).getBytes(), ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, keySpec);
		byte[] encode = Base64.getDecoder().decode(base64Data.getBytes());
		return new String(cipher.doFinal(encode));
	}

	/*
	public static void main(String[] args) throws Exception {
//		String A = "oSWxqqMF5lk2EF+gdrdt5wPrOru854za5XjHq5cUXs74zF9+jlxGOo7DHQIuntolVF3kQAruoMoNK5lLRsCulgG2hAT+6sNen8f/f3drMxfsTFOj3aBTKkIHs2p3AVJA4fXpGRCpejq3JJplSQnnSwFljzcxvqe7rU3y/H0KpFyBuYUSEf+msbkHEnHnIHQi4p9JDlLPWoKHramM7R65Qd13GdUU41scNybWCkwl+q/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